/**
 * 科室数据操作API
 * 用于管理绑定到3D模型的科室数据
 */

import { hospitalDB, DepartmentData } from '../indexedDB'

export interface CreateDepartmentRequest {
  hospitalId: string
  buildingId?: string
  floorId?: string
  name: string
  type: 'outpatient' | 'inpatient' | 'emergency' | 'surgery' | 'laboratory' | 'radiology' | 'pharmacy' | 'administration'
  position: [number, number]
  modelInfo?: {
    meshName: string
    boundingBox?: {
      min: [number, number, number]
      max: [number, number, number]
    }
  }
  description?: string
  contact?: {
    phone?: string
    hours?: string
    director?: string
  }
  capacity?: number
  status?: 'active' | 'inactive' | 'maintenance'
  metadata?: Record<string, any>
}

export interface UpdateDepartmentRequest extends Partial<CreateDepartmentRequest> {
  id: string
}

export interface DepartmentResponse {
  success: boolean
  msg: string
  data?: DepartmentData
}

export interface DepartmentsListResponse {
  success: boolean
  msg: string
  data?: DepartmentData[]
}

/**
 * 创建科室
 */
export const createDepartment = async (
  department: CreateDepartmentRequest
): Promise<DepartmentResponse> => {
  try {
    const data = await hospitalDB.addDepartment({
      ...department,
      status: department.status || 'active',
      metadata: department.metadata || {}
    })
    
    return {
      success: true,
      msg: '科室创建成功',
      data
    }
  } catch (error) {
    console.error('创建科室失败:', error)
    return {
      success: false,
      msg: '创建科室失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 根据医院ID获取科室列表
 */
export const getDepartmentsByHospital = async (
  hospitalId: string
): Promise<DepartmentsListResponse> => {
  try {
    const data = await hospitalDB.getDepartmentsByHospital(hospitalId)
    return {
      success: true,
      msg: '获取科室列表成功',
      data
    }
  } catch (error) {
    console.error('获取科室列表失败:', error)
    return {
      success: false,
      msg: '获取科室列表失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 根据建筑ID获取科室列表
 */
export const getDepartmentsByBuilding = async (
  buildingId: string
): Promise<DepartmentsListResponse> => {
  try {
    const data = await hospitalDB.getDepartmentsByBuilding(buildingId)
    return {
      success: true,
      msg: '获取建筑科室列表成功',
      data
    }
  } catch (error) {
    console.error('获取建筑科室列表失败:', error)
    return {
      success: false,
      msg: '获取建筑科室列表失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 根据楼层ID获取科室列表
 */
export const getDepartmentsByFloor = async (
  floorId: string
): Promise<DepartmentsListResponse> => {
  try {
    const data = await hospitalDB.getDepartmentsByFloor(floorId)
    return {
      success: true,
      msg: '获取楼层科室列表成功',
      data
    }
  } catch (error) {
    console.error('获取楼层科室列表失败:', error)
    return {
      success: false,
      msg: '获取楼层科室列表失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 更新科室信息
 */
export const updateDepartment = async (
  id: string,
  updates: Partial<CreateDepartmentRequest>
): Promise<DepartmentResponse> => {
  try {
    // 先获取现有数据
    const existing = await hospitalDB.getDepartment(id)
    if (!existing) {
      return {
        success: false,
        msg: '科室不存在'
      }
    }
    
    // 合并更新数据
    const updatedData: DepartmentData = {
      ...existing,
      ...updates,
      id,
      updatedAt: new Date()
    }
    
    await hospitalDB.updateDepartment(updatedData)
    
    return {
      success: true,
      msg: '科室更新成功',
      data: updatedData
    }
  } catch (error) {
    console.error('更新科室失败:', error)
    return {
      success: false,
      msg: '更新科室失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 删除科室
 */
export const deleteDepartment = async (id: string): Promise<DepartmentResponse> => {
  try {
    await hospitalDB.deleteDepartment(id)
    return {
      success: true,
      msg: '科室删除成功'
    }
  } catch (error) {
    console.error('删除科室失败:', error)
    return {
      success: false,
      msg: '删除科室失败: ' + (error instanceof Error ? error.message : '未知错误')
    }
  }
}

/**
 * 科室类型配置
 */
export const getDepartmentTypes = () => {
  return [
    { 
      type: 'outpatient', 
      label: '门诊科室', 
      icon: '🏥', 
      color: '#3b82f6',
      description: '门诊诊疗科室'
    },
    { 
      type: 'inpatient', 
      label: '住院科室', 
      icon: '🛏️', 
      color: '#10b981',
      description: '住院病区'
    },
    { 
      type: 'emergency', 
      label: '急诊科', 
      icon: '🚑', 
      color: '#ef4444',
      description: '急诊急救科室'
    },
    { 
      type: 'surgery', 
      label: '手术科室', 
      icon: '⚕️', 
      color: '#8b5cf6',
      description: '手术室和手术科室'
    },
    { 
      type: 'laboratory', 
      label: '检验科', 
      icon: '🔬', 
      color: '#f59e0b',
      description: '医学检验科室'
    },
    { 
      type: 'radiology', 
      label: '影像科', 
      icon: '📷', 
      color: '#06b6d4',
      description: '医学影像科室'
    },
    { 
      type: 'pharmacy', 
      label: '药房', 
      icon: '💊', 
      color: '#84cc16',
      description: '药房药剂科'
    },
    { 
      type: 'administration', 
      label: '行政科室', 
      icon: '🏢', 
      color: '#6b7280',
      description: '行政管理科室'
    }
  ]
}

/**
 * 科室状态选项
 */
export const getDepartmentStatusOptions = () => {
  return [
    { label: '正常运营', value: 'active', color: '#10b981' },
    { label: '暂停服务', value: 'inactive', color: '#f59e0b' },
    { label: '维护中', value: 'maintenance', color: '#ef4444' }
  ]
}